<template>
  <div>
    <div class="left-board border">
      <div class="left-scrollbar">
        <el-collapse
          v-model="activeCollapse"
          :accordion="true"
        >
          <el-collapse-item
            title="自定义控件"
            name="customControl"
          >
            <div class="btn-group">
              <div
                v-for="(item,index) in btnList"
                :key="'btn-item'+index"
                class="btn"
                @click="btnClick(item.component)"
              >
                <div class="btn-body">
                  {{ item.name }}
                </div>
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item
            title="定制控件"
            name="customizedControl"
          >
            <div class="btn-group">
              11111
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div class="center-board border">
      <div class="center-tool-bar border">
        <el-button
          type="danger"
          size="small"
          @click="clear"
        >
          清空
        </el-button>
      </div>
      <div class="center-scrollbar">
        <div class="form">
          <el-form
            ref="form"
            label-width="auto"
            :inline="false"
            size="normal"
            :model="form"
          >
            <el-form-item
              v-for="(item,index) in formList"
              :key="'form-item'+index"
              :label="item.label"
            >
              <el-input
                v-if="item.type==='input'"
                v-model="form[`${item.key}`]"
                :placeholder="`请输入${item.label}`"
              />
              <el-input
                v-if="item.type==='textarea'"
                v-model="form[`${item.key}`]"
                type="textarea"
                :placeholder="`请输入${item.label}`"
              />
              <el-select
                v-if="item.type === 'select'"
                v-model="form[`${item.key}`]"
                :placeholder="`请输入${item.label}`"
              >
                <el-option
                  v-for="(option,optionIndex) in item.options"
                  :key="`select-option-${optionIndex}`"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-date-picker
                v-if="item.type === 'dateTimePicker'"
                v-model="form[`${item.key}`]"
                type="datetime"
                :placeholder="`请输入${item.label}`"
                value-format="yyyy-MM-dd HH:mm:ss"
                align="right"
              />

              <el-checkbox-group
                v-if="item.type === 'checkBox'"
                v-model="form[`${item.key}`]"
              >
                <el-checkbox
                  v-for="(option,optionIndex) in item.options"
                  :key="`select-option-${optionIndex}`"
                  :label="option.label"
                  :value="option.value"
                />
              </el-checkbox-group>

              <div style="float:right">
                <el-button
                  type="text"
                  size="default"
                  @click="formItemEdit(index)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="default"
                  @click="formItemDelete(item.key,index)"
                >
                  删除
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="right-board border">
      <div class="right-scrollbar">
        <div class="form">
          <el-form
            v-if="Object.keys(currentRightForm).length > 0"
            ref="form"
            :model="currentRightForm"
            label-width="80px"
            :inline="false"
            size="normal"
          >
            <el-form-item label="标题">
              <el-input
                v-model="currentRightForm.title"
                @input="rightFormTitleInputChange($event,currentRightForm.key)"
              />
            </el-form-item>
            <el-form-item label="类型">
              <el-select
                v-model="currentRightForm.type"
                @input="rightFormTypeSelectChange($event,currentRightForm.key)"
              >
                <el-option
                  v-for="(item,index) in typeOption"
                  :key="'select_'+index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="currentRightForm.type === 'select'|| 'checkBox'"
              label="选项"
            >
              <div
                v-for="(option,optionIndex) in currentRightForm.options"
                :key="optionIndex"
              >
                <el-row style="margin-top:10px">
                  <el-col :span="12">
                    <el-input
                      v-model="option.label"
                      size="normal"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-input
                      v-model="option.value"
                      size="normal"
                    />
                  </el-col>
                  <el-col :span="4">
                    <el-button
                      type="danger"
                      size="default"
                      @click="rightFormOptionSubRow(currentRightForm.options,optionIndex)"
                    >
                      -
                    </el-button>
                  </el-col>
                </el-row>
              </div>
              <el-button
                type="primary"
                size="default"
                @click="rightFormOptionAddRow(currentRightForm.options)"
              >
                +
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-button
          type="primary"
          size="default"
          @click="test"
        >
          test
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: 0,
      activeCollapse: ['customControl'], // 默认展开的折叠面板
      formList: [], // 渲染表单的list
      form: {},
      btnList: [ // 左侧添加控件按钮的list
        {
          name: '单行文本',
          component: {
            label: '单行文本',
            type: 'input'
          }
        },
        {
          name: '多行文本',
          component: {
            label: '多行文本',
            type: 'textarea'
          }
        },
        {
          name: '下拉选择',
          component: {
            label: '下拉选择',
            type: 'select',
            options: [
              {
                label: '选项1',
                value: 1
              },
              {
                label: '选项2',
                value: 2
              }
            ]
          }
        },
        {
          name: '时间选择',
          component: {
            label: '时间选择',
            type: 'dateTimePicker'
          }
        },
        {
          name: '多选框',
          component: {
            label: '多选框',
            type: 'checkBox',
            options: [
              {
                label: '选项1',
                value: 1
              },
              {
                label: '选项2',
                value: 2
              }
            ]
          }
        },
      ],
      rightFormObjs: {}, // 这里面装着每一个渲染出来的控件的配置表单
      currentRightForm: {} // 当前的右侧表单
    }
  },
  computed: {
    typeOption() {
      const arr = this.btnList.map(item => {
        return item.component.type
      })
      return arr
    }
  },
  methods: {
    btnClick(component) { // 监听左侧btn的点击
      this.id += 1 // 用于标识每个form-item的id值自增+1
      const comP = Object.assign({}, component) // !!浅拷贝btnList的item的component属性，用于渲染form，如果使用深拷贝（直接赋值的方式）会改变btnList中对应item的component的值
      comP.key = `${component.type}_${this.id}` // 给即将push到formList中用于渲染的comP对象赋予一个唯一标识key
      this.formList.push(comP) // 将comP对象push到formList中用于渲染form
      this.rightFormObjs[`${comP.key}`] = { // 利用comP的唯一标识作为key，在rightFormObjs中创建一个对象，用于存放每一个form-item的配置对象，如form-item的label
        title: ''
      }
      // 从rightFormObjs取出当下刚刚添加的form-item的配置对象，存放在currentRightForm当中
      // 此处用的是深拷贝，也就是说currentRightForm与rightFormObjs中对应的值是‘双向绑定’的，任何一个变化都会引起另一个变化
      this.currentRightForm = this.rightFormObjs[`${comP.key}`]
      this.currentRightForm.key = comP.key // 把comP的key值赋值给currentRightForm的key，用于建立form-item与rightFormObjs中的配置项的唯一关联
      this.currentRightForm.title = comP.label
      this.currentRightForm.type = comP.type
      console.log(this.currentRightForm)
      console.log(this.formList)
      if (comP.options) {
        // this.currentRightForm.options = comP.options
        this.$set(this.currentRightForm, 'options', comP.options)
      }
    },
    clear() { // 清空动态表单
      if (this.formList.length === 0) {
        return false
      } else {
        this.$confirm('即将清空的数据不会保存，确定继续吗？', { title: '提示', type: 'warning' }).then(() => {
          this.formList = []
          this.rightFormObjs = {}
          this.currentRightForm = {}
          this.id = 0
          this.form = {}
          return true
        })
          .catch(() => {
            return false
          })
      }
    },
    rightFormTitleInputChange(e, key) { // 右侧表单的title input 发生变化
    //   console.log(e, key)
    //   const item = this.formList.find((item, index) => {
    //     return item.key === key
    //   })
      const foundIndex = this.formList.findIndex(item => {
        return item.key === key
      })
      this.formList[foundIndex].label = e
    },
    rightFormTypeSelectChange(e, key) {
      console.log(e)
      this.form[`${key}`] = ''
      const foundIndex = this.formList.findIndex(item => {
        return item.key === key
      })
      this.formList[foundIndex].type = e
      if (e === 'select' || e === "dateTimePicker") {
        this.$set(this.formList[foundIndex], 'options', []) // 如果不用set的方式，点击新增选项之后，选项的label和value输入框不可输入
        this.$set(this.currentRightForm, 'options', this.formList[foundIndex].options) // 这里是把formList的options深拷贝给currentRightForm的options，让两者双向绑定
        // this.formList[foundIndex].options = []
        // this.currentRightForm.options = []
      }
      console.log(this.formList[foundIndex])
    },
    formItemEdit(index) { // 编辑表单控件
      this.currentRightForm = this.rightFormObjs[`${this.formList[index].key}`] // 切换到对应的右侧表单，深拷贝
    },
    formItemDelete(key, index) { // 删除表单控件
      this.$confirm('确定删除吗？', { title: '提示', type: 'warning' }).then(() => {
        this.formList.splice(index, 1)
        this.currentRightForm = {}
        this.rightFormObjs = this._.omit(this.rightFormObjs, [key]) // 删除表单的配置表单
        this.form = this._.omit(this.form, [key])
      })
        .catch(() => {
          return
        })
    },
    rightFormOptionAddRow(options) {
      options.push({
        label: '',
        value: ''
      })
      this.$forceUpdate()
    },
    rightFormOptionSubRow(options, index) {
      options.splice(index, 1)
      this.$forceUpdate()
    },
    test() {
      console.log('formList',this.formList)
      console.log('currentRightForm',this.currentRightForm)
      console.log('rightFormObjs',this.rightFormObjs)
      console.log('typeOption',this.typeOption)
      console.log('form',this.form)
    }
  }
}
</script>

<style scoped>
@keyframes btn-body-hover {
  100% {
    filter: brightness(1.06);
  }
}
.border {
    border: 1px solid #f3f6f9;
}
.left-board {
    position: absolute;
    left: 0;
    top: 0;
    height:100vh;
    width: 240px;
}
.left-scrollbar {
    height: calc(100vh - 42px);
    overflow-y: scroll;
}
.center-board {
    height: 100vh;
    width: auto;
    margin: 0 360px 0 260px;
}
.center-scrollbar {
    height: calc(100vh - 42px);
    overflow-y: scroll;
    overflow-x: hidden;
}
.center-tool-bar {
    margin: 10px;
    padding: 10px;
}
.right-board {
    width:350px;
    position:absolute;
    right:0;
    top:0;
    height: 100vh;
}
.right-scrollbar {
    height: calc(100vh - 42px);
    overflow-y: scroll;
    overflow-x: hidden;
}
.btn-group {
    padding: 8px;
    height: 100%;
}
.btn {
    display: inline-block;
    width: 48%;
    margin: 1%;
}
.btn-body {
    text-align: center;
    font-size: 12px;
    cursor: pointer;
    border-radius: 5px;
    background-color: #67c23a;
    color:#fff
}
.btn-body:hover {
  animation-name: btn-body-hover;
  animation-duration: 100ms;
  animation-fill-mode: forwards;
}

.form {
    margin: 10px;
}
</style>
